#include "clockwidget.h"
#include "ui_clockwidget.h"
#include "windows.h"
#include "qdebug.h"
#include "numberhelper.h"

ClockWidget::ClockWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ClockWidget)
{
    ui->setupUi(this);
    // 界面设置
    setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    setAttribute(Qt::WA_TranslucentBackground);
    ::SetWindowPos(HWND(this->winId()), HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
    showFullScreen();
    // 设置定时器
    timer = new QTimer;
    timer->setInterval(1000);
    timer->start();
    connect(timer, &QTimer::timeout, this, [=](){
        this->update();
    });
    // HWND desktop = ::FindWindowEx(NULL, NULL, L"Progman", NULL);
    // ::SetParent((HWND)this->winId(), desktop);
}

void paintTimer(QPainter* painter, int time, int width = 0, int len = 0, QString preStr = "", QString sufStr = "")
{
    for(int i = 0; i < len; i++)
    {
        painter->save();
        painter->rotate(360 / len * i);
        painter->setPen(i?Qt::white:Qt::red);
        QString s = NumberHelper::numToStr(preStr, (time + i - 1) % len + 1, sufStr);
        painter->drawText(width, 0, QString("%1").arg(s));
        painter->restore();
    }
}

void ClockWidget::paintEvent(QPaintEvent *)
{
    QDateTime nowtime = QDateTime::currentDateTime();
    int year = nowtime.date().year();
    QString yearStr = NumberHelper::numToStrWithoutUnit("", year, "年");
    int month = nowtime.date().month();
    int day = nowtime.date().day();
    int week = nowtime.date().dayOfWeek();
    int hour = nowtime.time().hour();
    int minute = nowtime.time().minute();
    int second = nowtime.time().second();
    // 界面宽高
    int width = this->width();
    int height = this->height();
    // 画家配置
    QPainter painter(this);
    painter.setFont(QFont("宋体", 12));
    painter.setPen(Qt::black);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.translate(width / 2, height / 2);
    // 计算年份
    QFontMetrics metrics = painter.fontMetrics();
    int m_width = metrics.width(yearStr);
    painter.setPen(Qt::red);
    painter.drawText(-m_width / 2, 0, yearStr);
    // 计算月份
    paintTimer(&painter, month, 80, 12, "", "月");
    // 计算日期
    paintTimer(&painter, day, 160, 30, "", "日");
    // 计算星期
    paintTimer(&painter, week, 240, 7, "星期", "");
    // 计算小时
    paintTimer(&painter, hour, 320, 24, "", "时");
    // 计算分钟
    paintTimer(&painter, minute, 400, 60, "", "分");
    // 计算秒
    paintTimer(&painter, second, 480, 60, "", "秒");
}

ClockWidget::~ClockWidget()
{
    timer->stop();
    delete timer;
    delete ui;
}

